package com.dormitory.ui;

import com.dormitory.model.Building;
import com.dormitory.service.BuildingService;
import com.dormitory.service.impl.BuildingServiceImpl;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class BuildingPanel extends JPanel {
    private BuildingService buildingService;
    private JTable buildingTable;
    private DefaultTableModel tableModel;
    private JTextField searchField;
    private JTextField nameField;
    private JTextField floorsField;
    private JTextField descriptionField;
    private JPanel resultStatsPanel;

    public BuildingPanel() {
        buildingService = new BuildingServiceImpl();
        initUI();
        loadBuildingData();
    }

    private void initUI() {
        setLayout(new BorderLayout());
        // 工具栏
        JToolBar toolBar = createToolBar();
        add(toolBar, BorderLayout.NORTH);
        
        // 创建结果统计面板
        resultStatsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        resultStatsPanel.setBorder(BorderFactory.createTitledBorder("搜索结果统计"));
        add(resultStatsPanel, BorderLayout.SOUTH);
        
        // 表格
        createTable();
        JScrollPane scrollPane = new JScrollPane(buildingTable);
        add(scrollPane, BorderLayout.CENTER);
    }

    private JToolBar createToolBar() {
        JToolBar toolBar = new JToolBar();
        toolBar.setFloatable(false);

        // 搜索框
        searchField = new JTextField(20);
        JButton searchButton = new JButton("搜索");
        searchButton.addActionListener(e -> searchBuildings());

        // 添加按钮
        JButton addButton = new JButton("添加");
        addButton.addActionListener(e -> showAddDialog());

        // 修改按钮
        JButton editButton = new JButton("修改");
        editButton.addActionListener(e -> showEditDialog());

        // 删除按钮
        JButton deleteButton = new JButton("删除");
        deleteButton.addActionListener(e -> deleteBuilding());

        toolBar.add(new JLabel("搜索："));
        toolBar.add(searchField);
        toolBar.add(searchButton);
        toolBar.addSeparator();
        toolBar.add(addButton);
        toolBar.add(editButton);
        toolBar.add(deleteButton);

        return toolBar;
    }

    private void createTable() {
        String[] columnNames = {"楼栋编号", "楼栋名称", "总层数", "楼栋类型"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        buildingTable = new JTable(tableModel);
        buildingTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }

    private void loadBuildingData() {
        tableModel.setRowCount(0);
        List<Building> buildings = buildingService.getAllBuildings();
        for (Building building : buildings) {
            addBuildingToTable(building);
        }
        // 显示全部数据的统计信息
        updateSearchStats(buildings, "");
    }

    private void addBuildingToTable(Building building) {
        Object[] rowData = {
            building.getBuildingId(),
            building.getBuildingName(),
            building.getTotalFloors(),
            building.getBuildingType()
        };
        tableModel.addRow(rowData);
    }

    private void searchBuildings() {
        String condition = searchField.getText().trim();
        tableModel.setRowCount(0);
        List<Building> buildings = buildingService.searchBuildings(condition);
        
        // 更新表格数据
        for (Building building : buildings) {
            addBuildingToTable(building);
        }
        
        // 更新统计信息
        updateSearchStats(buildings, condition);
    }

    private void updateSearchStats(List<Building> buildings, String searchCondition) {
        resultStatsPanel.removeAll();
        
        // 创建统计信息标签
        JLabel totalLabel = new JLabel(String.format("总楼栋数: %d", buildings.size()));
        JLabel searchLabel = new JLabel(String.format("搜索条件: %s", searchCondition.isEmpty() ? "全部" : searchCondition));
        
        // 按楼层统计
        Map<Integer, Long> floorStats = buildings.stream()
            .collect(Collectors.groupingBy(Building::getTotalFloors, Collectors.counting()));
        JLabel floorLabel = new JLabel("楼层分布: " + 
            floorStats.entrySet().stream()
                .map(e -> String.format("%d层(%d栋)", e.getKey(), e.getValue()))
                .collect(Collectors.joining(", ")));
        
        // 添加统计信息到面板
        resultStatsPanel.add(totalLabel);
        resultStatsPanel.add(new JLabel(" | "));
        resultStatsPanel.add(searchLabel);
        resultStatsPanel.add(new JLabel(" | "));
        resultStatsPanel.add(floorLabel);
        
        // 刷新面板
        resultStatsPanel.revalidate();
        resultStatsPanel.repaint();
    }

    private void showAddDialog() {
        BuildingFormDialog dialog = new BuildingFormDialog(SwingUtilities.getWindowAncestor(this), null);
        dialog.setVisible(true);
        if (dialog.isConfirmed()) {
            Building building = dialog.getBuilding();
            if (buildingService.addBuilding(building)) {
                JOptionPane.showMessageDialog(this, "添加成功！");
                loadBuildingData();
            } else {
                JOptionPane.showMessageDialog(this, "添加失败！");
            }
        }
    }

    private void showEditDialog() {
        int selectedRow = buildingTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要修改的楼栋！");
            return;
        }
        Integer buildingId = (Integer) tableModel.getValueAt(selectedRow, 0);
        Building building = buildingService.getBuildingById(buildingId);
        if (building == null) {
            JOptionPane.showMessageDialog(this, "未找到楼栋信息！");
            return;
        }
        BuildingFormDialog dialog = new BuildingFormDialog(SwingUtilities.getWindowAncestor(this), building);
        dialog.setVisible(true);
        if (dialog.isConfirmed()) {
            Building updated = dialog.getBuilding();
            updated.setBuildingId(buildingId);
            if (buildingService.updateBuilding(updated)) {
                JOptionPane.showMessageDialog(this, "修改成功！");
                loadBuildingData();
            } else {
                JOptionPane.showMessageDialog(this, "修改失败！");
            }
        }
    }

    private void deleteBuilding() {
        int selectedRow = buildingTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要删除的楼栋！");
            return;
        }

        int confirm = JOptionPane.showConfirmDialog(this,
            "确定要删除这栋楼吗？", "确认删除",
            JOptionPane.YES_NO_OPTION);
        
        if (confirm == JOptionPane.YES_OPTION) {
            Integer buildingId = (Integer) tableModel.getValueAt(selectedRow, 0);
            if (buildingService.deleteBuilding(buildingId)) {
                JOptionPane.showMessageDialog(this, "删除成功！");
                loadBuildingData();
            } else {
                JOptionPane.showMessageDialog(this, "删除失败！");
            }
        }
    }
} 